package com.zzgele.qmzb.api.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.zzgele.qmzb.api.bean.PackageCount;
import com.zzgele.qmzb.api.core.AbstractService;
import com.zzgele.qmzb.api.dao.BonusMapper;
import com.zzgele.qmzb.api.model.Bonus;
import com.zzgele.qmzb.api.model.BonusPackage;
import com.zzgele.qmzb.api.service.BonusPackageService;
import com.zzgele.qmzb.api.service.BonusService;
import com.zzgele.qmzb.api.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Created by Martin on 2017/07/14.
 */
@Service(interfaceClass = BonusService.class,proxy="jdk")
@Component
public class BonusServiceImpl extends AbstractService<Bonus> implements BonusService {
    @Resource
    private BonusMapper bonusMapper;

    private  final Logger logger = LoggerFactory.getLogger(BonusServiceImpl.class);
     @Resource
     private BonusService bonusService;
    @Resource
    private BonusPackageService bonusPackageService;
    public  ConcurrentHashMap<Long,PackageCount> PackageHashMap=new ConcurrentHashMap(100);

    public Bonus getOneBonus(Long uid, Long bonusPackageId) {
        //红包id 为key创建concurrentHashmap
        Bonus bonus=null;
        logger.debug("getOneBonus");
        Integer a=bonusMapper.selectBonusByFromPackage(bonusPackageId,uid);
        if(a==1) {
            bonus=new Bonus();
            bonus.setStatus(602);
            return bonus;
        }
        PackageCount packageCount=new PackageCount();
        PackageCount packageCount2;
        if(!PackageHashMap.containsKey(bonusPackageId)) {
            packageCount2=PackageHashMap.putIfAbsent(bonusPackageId, packageCount);
            if(packageCount2==null){
                packageCount2=packageCount;
            }
        }else{
            packageCount2=PackageHashMap.get(bonusPackageId);
        }
        int currrentBonussize = getCurrentBoundCountByFromPackageId(bonusPackageId);
        BonusPackage bonusPackage = bonusPackageService.getBonusPackageById(bonusPackageId);
        if(bonusPackage==null)
        {
            PackageHashMap.remove(bonusPackageId);
            return  null;
        }
        int bonusAmount = bonusPackage.getAmount();
        packageCount2.setAmount(bonusAmount);
        packageCount2.setCurrentCount(currrentBonussize);

        logger.info("uid{}的用户进入计数器-bonusPackageId{}", uid, bonusPackageId);
        //原子计算红包数量
        int currentAmount=packageCount2.compareAndIncrement();
        if(currentAmount!=-1) {
            logger.info("uid{}。分配红包开始 计数自增 当前计数{}", uid,currentAmount);
            bonus = getOneBonusWithoutLock(uid, bonusPackageId);
            if(bonus==null) {
                currentAmount=packageCount2.decrementCurrentCount();
                logger.info("uid{}。分配红包失败 计数自减 当前计数{}.", uid,currentAmount);
            }

        }
        logger.info("uid{}的用户退出计数器-bonusPackageId{}", uid, bonusPackageId);
        if(packageCount2.getAmount()==packageCount2.getCurrentCount()){
            //红包发放结束，移出hashmap
            if(PackageHashMap.containsKey(bonusPackageId)){
                PackageHashMap.remove(bonusPackageId);
                logger.debug("当前缓存大小"+PackageHashMap.size());
            }
        }
        return bonus;
    }
    /**
     * 根据bonusPackageId查到红包详情后，生成一个红包，插入数据库并返回。
     *
     * @param bonusPackageId 必填
     * @return
     */
    private Bonus getOneBonusWithoutLock(Long uid, Long bonusPackageId) {
        logger.info("{}uid 来抢{}红包", uid, bonusPackageId);
        Bonus bonus = new Bonus();
//        bonus.setExpireTime(expiredTime);
        BonusPackage bonusPackage =bonusPackageService.findById(bonusPackageId); // bonusPackageMapper.selectBonusPackageById(bonusPackageId);
        int currrentBonussize = bonusMapper.selectCurrentBonusCountByFromPackageId(bonusPackageId);
        if (bonusPackage == null) {
            logger.info("packageId不存在，返回");
            return null;
        }
        int price = compute(bonusPackage, currrentBonussize);
        if (price == 0) {
            logger.info("红包已被抢完");
            return null;
        }
        bonus.setExpireTime(bonusPackage.getExpireTime());
        bonus.setCreateTime(DateUtil.getCurUnixTimeStampInt());
        bonus.setPackageId(bonusPackageId);
        bonus.setPrice(price);
        bonus.setStatus(0);
        bonus.setUid(uid);
        bonusMapper.insert(bonus);

        return bonus;
    }
    public int getCurrentBoundCountByFromPackageId(Long packageId) {
        int CurrentBounsCount = bonusMapper.selectCurrentBonusCountByFromPackageId(packageId);
        return CurrentBounsCount;
    }


    public int compute(BonusPackage bonusPackage, int size) {
        String prePrice = bonusPackage.getPrePrice();
        Integer curPrice = 0;
        String[] comPrice = prePrice.split(",");
        if (size == comPrice.length) {
            curPrice = 0;
        } else if (size < comPrice.length) {
            logger.debug("comPrice[0] :{}", comPrice[0]);
            if (comPrice.length > 1) {
                logger.debug("comPrice[1] :{}", comPrice[1]);
            }
            curPrice = Integer.valueOf(comPrice[size]);
        }
        return curPrice;
    }
}
